﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using HomeStayWebCP.Models;
using DAL;
using System.IO;
using HomeStayWebCP.Models.BusinessObject;
using HomeStayWebCP.Utility;
using HomeStayWebCP.Mailers;


namespace HomeStayWebCP.Controllers
{
    public class UsersController : Controller
    {
        //
        // GET: /Users/
        CryptorEngine crytor = new CryptorEngine();
        public ActionResult Index()
        {
            return View();
        }
       
        [HttpPost]
        public String CheckExistUser(string username)
        {
            UserModel model = new UserModel();
            string usernamecheck = username.Trim().ToLower();
            User listuser = model.SelectUserbyUserName(usernamecheck);
            if (listuser != null)
                //return Json(new { returnvalue = true });
                return "Exist";
            else
            {
                //return Json(new { returnvalue = false });
                return "NotExist";
            }

        }

        //Select User

        //Creat new User--Register
        public ActionResult CreateUser(UserObject userobj)
        {
         
            UserModel model = new UserModel();
            User user = new User();
               
            if (ModelState.IsValid)
            {
                user.RoleID = 1;
                user.IsDeleted = false;
                user.Username = userobj.Username.Trim().ToLower();
                user.Password = crytor.Encrypt(userobj.Password, true);
                user.Email = userobj.Email.Trim().ToLower();
                user.Fullname = userobj.Fullname;
                user.Gender = userobj.Gender;
                user.Phone = userobj.Phone;
                user.Address = userobj.Address;
                user.TimeCreated = DateTime.Now;
                //set status cho user la dang cho duyet
                //upload image

                HttpPostedFileBase file = Request.Files[0];
                if (!file.FileName.Equals(""))
                {
                    string filename = user.Username + ".jpg";
                    byte[] imageSize = new byte[file.ContentLength];
                    file.InputStream.Read(imageSize, 0, (int)file.ContentLength);
                    var path = Path.Combine(Server.MapPath("~/Content/images/AvatarUser/"), filename);
                    file.SaveAs(path);
                    user.AvatarPicture = filename;
                }
                else
                {
                    user.AvatarPicture = Util.imageAvatarDefault;
                }

                model.InsertUser(user);
                //auto login after register
                HttpContext.Session.Add("username", user.Username);
                return RedirectToAction("Index", "Home");

            }
            return View(userobj);

        }

        public ActionResult Register()
        {

            return PartialView("CreateUser");
        }

        //Log off function
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            Session["username"] = null;
            //Session["userID"] = null;
            return RedirectToAction("Index", "Home");
        }

        public String CheckEmailExist(string email)
        {
            UserModel model = new UserModel();
            string emailcheck = email.ToLower();
            if (model.CheckEmailExist(emailcheck) == true)
            {
                return "Exist";
            }
            return "NotExist";

        }

        public String CheckUserLogin(string usernameinput, string password, string url)
        {
            UserModel model = new UserModel();
            string username = usernameinput.Trim().ToLower();
            string passwordlogin = password.ToLower();
            User listuser = model.SelectUserbyUserName(username);
            if (listuser != null)
            {
                string passwordcheck = crytor.Decrypt(listuser.Password, true);
                if (listuser.Username == username && passwordcheck == passwordlogin && listuser.IsDeleted == false)
                {
                    HttpContext.Session.Add("username", username);
                    return "Success";
                }
                else
                {
                    return "Fail";
                }


            }
            return "Fail";
        }

        public ActionResult CaptchaImage(string prefix, bool noisy = true)
        {
            var rand = new Random((int)DateTime.Now.Ticks);

            //generate new question
            int a = rand.Next(10, 99);
            int b = rand.Next(0, 9);
            var captcha = string.Format("{0} + {1} = ?", a, b);

            //store answer
            //Session["Captcha" + prefix] = a + b;
            Session["Captcha"] = a + b;
            //image stream
            FileContentResult img = null;

            using (var mem = new MemoryStream())
            using (var bmp = new Bitmap(130, 30))
            using (var gfx = Graphics.FromImage((System.Drawing.Image)bmp))
            {
                gfx.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
                gfx.SmoothingMode = SmoothingMode.AntiAlias;
                gfx.FillRectangle(Brushes.White, new Rectangle(0, 0, bmp.Width, bmp.Height));

                //add noise
                if (noisy)
                {
                    int i, r, x, y;
                    var pen = new Pen(Color.Yellow);
                    for (i = 1; i < 10; i++)
                    {
                        pen.Color = Color.FromArgb(
                        (rand.Next(0, 255)),
                        (rand.Next(0, 255)),
                        (rand.Next(0, 255)));

                        r = rand.Next(0, (130 / 3));
                        x = rand.Next(0, 130);
                        y = rand.Next(0, 30);

                        gfx.DrawEllipse(pen, x - r, y - r, r, r);
                    }
                }

                //add question
                gfx.DrawString(captcha, new Font("Tahoma", 15), Brushes.Gray, 2, 3);

                //render as Jpeg
                bmp.Save(mem, System.Drawing.Imaging.ImageFormat.Jpeg);
                img = this.File(mem.GetBuffer(), "image/Jpeg");
            }
            
            return img;
        }

        public String CheckCaptcha(string value)
        {
           
            string cap = Session["Captcha"].ToString();
            if (value == cap)
            {
                return "Right";
            }
            return "Wrong";
           
        }

        //public ActionResult MyAccount(int userid)
        public ActionResult MyAccount()
        {
            string username;
            UserObject userobj = new UserObject();
            if (HttpContext.Session["username"] != null && !HttpContext.Session["username"].ToString().Equals(""))
            {
                username = HttpContext.Session["username"].ToString();
                UserModel umodel = new UserModel();
                User user = umodel.SelectUserbyUserName(username); 
                userobj.Username = user.Username;
                userobj.Gender = user.Gender;
                userobj.AvatarPicture = user.AvatarPicture;
                userobj.Fullname = user.Fullname;
                userobj.Phone = user.Phone;
                userobj.Email = user.Email;
                userobj.Address = user.Address;
                userobj.Password = user.Password;
                var gender = new List<SelectListItem>();
                gender.Add(new SelectListItem { Value = "Female", Text = "Female"});
                gender.Add(new SelectListItem { Value = "Male", Text = "Male" });
                gender.Add(new SelectListItem { Value = "Other", Text = "Other" });

                ViewBag.GenderList = gender;

            }
            else
            {
                //error message
            }
          return View("MyAccount", userobj);
        }

        //public  ActionResult EditAccount(UserObject userobj)
        [HttpPost]
        public ActionResult MyAccount(UserObject userobj)

        {
            var gender = new List<SelectListItem>();
            gender.Add(new SelectListItem { Value = "Female", Text = "Female" });
            gender.Add(new SelectListItem { Value = "Male", Text = "Male" });
            gender.Add(new SelectListItem { Value = "Other", Text = "Other" });

            ViewBag.GenderList = gender;
       
            if (ModelState.IsValid)
            {
                if (HttpContext.Session["username"] != null && !HttpContext.Session["username"].ToString().Equals(""))
                {
                    UserModel umodel = new UserModel();
                    userobj.Username = HttpContext.Session["username"].ToString();
                    HttpPostedFileBase file = Request.Files["test"];
                    if (file != null && !file.FileName.Equals(""))
                    {
                        string filename = userobj.Username + ".jpg";
                        byte[] imageSize = new byte[file.ContentLength];
                        file.InputStream.Read(imageSize, 0, (int) file.ContentLength);
                        var path = Path.Combine(Server.MapPath("~/Content/images/AvatarUser/"), filename);
                        file.SaveAs(path);
                        userobj.AvatarPicture = filename;

                    }

                    umodel.Updateuser(userobj);
                    ViewBag.Message = "Change successfull!";

                }
                else
                {
                    ViewBag.Message = "Change Fail!";
                }
            }
            return View("MyAccount",userobj);
        }
      
        public String ChangePass(string oldpass,string newpass)
        {
            User user=new User();
            bool result;
            if (HttpContext.Session["username"] != null && !HttpContext.Session["username"].ToString().Equals(""))
            {
                UserModel umodel = new UserModel();
                string username = HttpContext.Session["username"].ToString();
                user = umodel.SelectUserbyUserName(username);
                string checkpass = crytor.Decrypt(user.Password, true);
                string newPassEncrypt = crytor.Encrypt(newpass, true);
                if (checkpass == oldpass)
                {
                    result = umodel.UpdatePassword(username, newPassEncrypt);
                    return (result == true) ? "Ok" : "Fail";
                }
                else
                {
                    return "WrongPass";
                }

            }
            return "Fail";

        }
        //public 

        public ActionResult Forgotpassword ()
        {
            return PartialView("Forgotpassword");
        }

        public string Checkmailforgotpass (string email)
        {
            MyMailer mailer = new MyMailer();
            UserModel model = new UserModel();
            string emailcheck = email.Trim().ToLower();
            User listuser = model.SelectUserByEmail(emailcheck);
            if (listuser != null)
            {
                string username = listuser.Username;
                string password = crytor.Decrypt(listuser.Password, true);
                mailer.MailForgotPass(username, password, emailcheck).Send();
                return "Exist";
            }
                
            else
            {
                
                return "NotExist";
            }
        }
    }
}
